from rest_framework.response import Response
from rest_framework import status,viewsets
from  rest_framework.decorators import api_view,action
from .models import Snippet,Menu
from .serializer import SnippetSerializer,MenuSerializer
from rest_framework.permissions import IsAuthenticated

import logging
#测试request对象
@api_view(['GET','POST'])
def Request(request,*args,**kwargs):
    if request.method=='GET':
        user=request.user
        print(user)
        return Response(data=None)
    else:
        return Response(data=None)


#测试用例
@api_view(['GET','POST'])
def snippet_list(request):
    if request.method=='GET':
        snippet=Snippet.objects.all()

        serializer=SnippetSerializer(snippet,many=True)

        return  Response(serializer.data)


    elif request.method=='POST':
         serializer=SnippetSerializer(data=request.data)
         if serializer .is_valid():
             serializer.save()

             return Response(serializer.data,status=status.HTTP_201_CREATED)

         return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)




class MenuView(viewsets.ModelViewSet):
    '''
    功能菜单模型类
    1、新增
    2、查询单个功能菜单
    3、查询所有功能菜单
    4、查询某个父菜单下面的所有子菜单列表
    5、查询所有的顶级菜单列表
    6、删除某一个功能菜单
    7、批量删除多个功能菜单, 传参：ids=[1,2,3]
    8、修改功能菜单


    '''
    queryset = Menu.objects.filter(delete_flag=0).all()
    serializer_class=MenuSerializer
    permission_classes = [IsAuthenticated]

    #查询所有功能菜单 查询某个父菜单下的所有子菜单列表  查询所有的顶级菜单

    def get_queryset(self):
        par=self.request.query_params.get('pid',None)

        if par:
            pid=int(par)
            #查询所有的顶级菜单
            if pid==0:
                return Menu.objects.filter(parent__isnull=True,delete_flag=0).all()
            #查询所有的父菜单下的子菜单
            else:
                return Menu.objects.filter(parent_id=pid,delete_flag=0).all()
        #返回所有未被标记删除的数据
        else:
            return Menu.objects.filter(delete_flag=0).all()

    def destroy(self, request, *args, **kwargs):

        menu = self.get_object()
        print(menu)


        menu.delete_flag = '1'
        menu.save()
        Menu.objects.filter(parent_id=menu.id).update(delete_flag=1)
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['delete'],detail=False)
    def multiple_delete(self,request,*args,**kwargs):
        delete_ids=request.data.get('ids')
        if not delete_ids:
            return Response(data={'detail': '参数错误,ids为必传参数'}, status=status.HTTP_400_BAD_REQUEST)

        elif not isinstance(delete_ids,list):
            return Response(data={'detail': 'ids格式错误,必须为List'}, status=status.HTTP_400_BAD_REQUEST)


        #先删除传递过来的功能菜单
        Menu.objects.filter(id__in=delete_ids).update(delete_flag=1)
        # 删除 所有的子功能菜单
        for m_id in delete_ids:
            Menu.objects.filter(parent__id=m_id).update(delete_flag=1)
        return Response(status=status.HTTP_204_NO_CONTENT)





